<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Admin;
use Illuminate\Support\Facades\Cache;

class LoginController extends Controller
{
    public function login()
    {
        $credentials = request(['username', 'password']);
        $token = auth('admin')->attempt($credentials);
        if ($token) {
            $user = auth('admin')->user();
            return $this->successful(compact('token', 'user'));
        }
        return $this->fail('用户名或密码错误');
    }

    public function register()
    {
        $nickname = request('nickname');
        $username = request('username');
        $password = request('password');
        $password = bcrypt($password);
        if ($username == '' || $password == '') {
            return $this->fail('参数不能为空(username, password)');
        }
        if (Admin::where('username', $username)->first()) {
            return $this->fail('用户名已存在');
        }

        $nickname = $nickname ? $nickname : $username;
        $data = compact('nickname', 'username', 'password');
        $info = Admin::create($data);
        return $this->successful($info);
    }

    public function repassword()
    {
        $admin = auth('admin')->user();
        if (!$admin) return $this->fail('请先登录');

        $password = request('password');
        Admin::where('id', $admin->id)->update([
            'password' => bcrypt($password)
        ]);
        return $this->successful();
    }

    /**
     * 重置密码
     *
     * @param string $email 邮箱
     * @param int $code 验证码
     * @param string $password 密码
     * @param string $repassword 确认密码
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function forget()
    {
        $email = request('email');
        $code = intval(request('code'));
        $password = request('password');
        $repassword = request('repassword');

        if (!$email || !$code || !$password || !$repassword) {
            return $this->fail('参数不能为空(email, code, password, repassword)');
        }
        if ($password != $repassword) return $this->fail('两次密码输入不一致');


        $cacheKey = 'mail:code:' . $code;
        $cacheData = Cache::get($cacheKey);
        logger($cacheKey, (array)$cacheData);

        if (!$cacheData) return $this->fail('邮箱验证码错误或不存在');
        if (time() > $cacheData['expired']) return $this->fail('邮箱验证码已过期');
        if ($code !== $cacheData['code']) return $this->fail('邮箱验证码错误');
        Cache::forget($cacheKey); // 验证码使用后销毁

        $admin = Admin::where('email', $email)->first();
        if (!$admin) return $this->fail('邮箱不存在');

        $admin->password = bcrypt($password);
        $admin->save();
        return $this->successful(null, '密码修改成功');
    }
}
